package com.atguigu.tingshu.user.ItemTypeStrategy.impl;

import java.util.List;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.ItemTypeStrategy.ItemTypeStrategy;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("1003")
public class VipTypeStrategyImpl implements ItemTypeStrategy {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Override
    public void SavePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        String orderNo = userPaidRecordVo.getOrderNo();
        Long userId = userPaidRecordVo.getUserId();
        String itemType = userPaidRecordVo.getItemType();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        QueryWrapper<UserVipService> vipServiceQueryWrapper = new QueryWrapper<>();
        vipServiceQueryWrapper.eq("order_no", orderNo);
        Long l = userVipServiceMapper.selectCount(vipServiceQueryWrapper);
        if (l > 0) {
            return;
        }
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userId);
        userVipService.setOrderNo(orderNo);

        UserInfo userInfo = userInfoMapper.selectById(userId);
        Date vipExpireTime = userInfo.getVipExpireTime();
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(itemIdList.get(0));
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        if (userInfo.getIsVip() == 1 && vipExpireTime.after(new Date())) {
            //如果是VIP
            userVipService.setStartTime(vipExpireTime);

            DateTime dateTime = DateUtil.offsetMonth(vipExpireTime, serviceMonth);
            userVipService.setExpireTime(dateTime);

        } else {
            userVipService.setStartTime(new Date());
            DateTime dateTime = DateUtil.offsetMonth(new Date(), serviceMonth);
            userVipService.setExpireTime(dateTime);

        }
        userVipServiceMapper.insert(userVipService);
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        userInfoMapper.updateById(userInfo);


    }
}
